package com.fengchunge.service.impl;

import com.google.common.collect.Lists;
import com.fengchunge.service.IFileService;
import com.fengchunge.util.FTPUtil;
import com.fengchunge.util.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @description:
 * @author: mingtai
 * @createDate: 4:48 2020/3/15
 * @version: 1.0
 */

@Service("iFileService")
@Slf4j
public class FileServiceImpl implements IFileService {

    @Override
    public String upload(MultipartFile file, String path) {
        String fileName = file.getOriginalFilename();
        //扩展名，abc.jpg
        String fileExtensionName = fileName.substring(fileName.lastIndexOf(".") + 1);
        String uploadFileName = UUIDUtils.generatorId() + "." + fileExtensionName;
        log.info("开始上传文件，上传文件的文件名:{}，上传的路径:{}，新文件名:{}", fileName, path, uploadFileName);

        File fileDir = new File(path);
        if (!fileDir.exists()) {
            fileDir.setWritable(true);
            fileDir.mkdirs();
        }

        log.info("文件夹路径：fileDir = {}", fileDir);
        File targetFile = new File(path, uploadFileName);
        boolean exists = targetFile.exists();
        log.info("目标文件targetFile = {} ,exists = {}", targetFile, exists);
        try {
            //上传文件到upload文件夹下面
            file.transferTo(targetFile);
            log.info("文件上传成功 targetFile = {}", targetFile);

            //上传targetFile文件到FTP服务器上
            FTPUtil.uploadFile(Lists.newArrayList(targetFile));
            log.info("已经上传到ftb服务器上了");
            //已经上传到ftb服务器上了

            //上传完成后，删除upload下面的文件，可以不删文件夹。
            targetFile.delete();

        } catch (IOException e) {
            log.error("上传文件异常", e);
            return null;
        }
        return targetFile.getName();
    }

}



